package similan.br19;

import java.io.Serializable;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

@ManagedBean(name = "orderListBackingBean")
@ViewScoped
public class OrderListBackingBean implements Serializable {

	private static final long serialVersionUID = 4772435037611617625L;

	private Prioritable[] prioritables;

	public Prioritable[] getPrioritables() {
		return prioritables;
	}

	public void setPrioritables(Prioritable[] prioritables) {
		this.prioritables = prioritables;
	}

	public void firstPriority(List<Prioritable> originalList) {
		Integer max = originalList.get(0).getPriority();
		for (Prioritable prioritable : prioritables) {
			prioritable.setPriority(1 + max);
			max = prioritable.getPriority();
		}
	}

	public void lastPriority(List<Prioritable> originalList) {
		Integer min = originalList.get(originalList.size() - 1).getPriority();
		for (Prioritable prioritable : prioritables) {
			if (min > 0) {
				prioritable.setPriority(min - 1);
				min = prioritable.getPriority();
			} else {
				prioritable.setPriority(0);
			}
		}
	}

	public void incrementPriority() {
		for (Prioritable prioritable : prioritables) {
			prioritable.setPriority(prioritable.getPriority() + 1);
		}
	}

	public void decrementPriority() {
		for (Prioritable prioritable : prioritables) {
			if (prioritable.getPriority() > 0) {
				prioritable.setPriority(prioritable.getPriority() - 1);
			}
		}
	}

	public void sort(List<Prioritable> sortList) {
		Collections.sort(sortList, new ComparePrioritable());
	}

	private class ComparePrioritable implements Comparator<Prioritable> {

		@Override
		public int compare(Prioritable p1, Prioritable p2) {
			if (p1.getPriority() > p2.getPriority()) {
				return -1;
			} else if (p1.getPriority() < p2.getPriority()) {
				return 1;
			}
			return 0;
		}
	}

}
